package part15;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wcj
 * @Date 2021/5/30 21:26
 * @Version 1.0
 */
public class Part1539 {
    public static void main(String[] args) throws NoSuchMethodException {
        List<Shape> shapes = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            shapes.add(new Shape());
        }
        Apply.apply(shapes, Shape.class.getMethod("rotate"));
        Apply.apply(shapes, Shape.class.getMethod("resize", int.class), 5);
        List<Square> squares = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            squares.add(new Square());
        }

        Apply.apply(squares, Shape.class.getMethod("rotate"));
        Apply.apply(squares, Shape.class.getMethod("resize", int.class), 5);
    }
}

/**
 * 实现呢一个静态方法，该方法可以将任何方法用于任意的对象的序列
 * 反射的实现很优雅，但是因为反射大多数动作都发生在运行时，因此要比使用非反射慢一点
 */
class Apply {
    public static <T, S extends Iterable<? extends T>> void apply(S seq, Method f, Object... args) {
        try {
            for (T t : seq) {
                f.invoke(t, args);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

class Shape {
    public void rotate() {
        System.out.println(this + "rotate");
    }

    public void resize(int size) {
        System.out.println(this + "resize:" + size);
    }
}

class Square extends Shape {
}

class FieldList<T> extends ArrayList<T> {
    public FieldList(Class<? extends T> type, int size) {
        try {
            for (int i = 0; i < size; i++) {
                this.add(type.newInstance());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
